package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Sku;
import com.itheima.service.SkuService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/findAll")
public class WebController {

    private RestHighLevelClient client;

    @Autowired
    private SkuService skuService;

    @GetMapping("/find")
    public void findAll() throws IOException {
        client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("192.168.200.129", 9200, "http"))
        );
        List<Sku> skus = skuService.list();

        //2. 创建BulkRequest对象
        BulkRequest request = new BulkRequest();
        //3. 创建多个IndexRequest对象，组织文档数据，并添加到BulkRequest中
        for (Sku sku : skus) {
            request.add(new IndexRequest("sku")
                    .id(sku.getId())
                    .source(JSON.toJSONString(sku), XContentType.JSON)
            );

        }
        //4. 发起请求
        client.bulk(request, RequestOptions.DEFAULT);

        client.close();
    }
}
